// {a:1,b:1} => ?a=1&b=1
export function jsonToString(json){
  if(typeof(json) != "object")
    return "";
  var filedNum = 0;
  var str = "?";
  for (const item in json)
    if (json.hasOwnProperty(item)) {
      filedNum++;
      str+=item+"="+json[item]+"&";
    }
  str = str.substr(0,str.length-1);
  if(filedNum>0)
    return str
  else
    return ""
}

//随机数
/***
*liveProbability: 0~10  true的概率
*/
export function liveOrDie(liveProbability){
  debugger;
  if(!liveProbability)
    liveProbability = 5
  if(liveProbability < 10 && liveProbability >= 1)
    return Math.random()*10 < liveProbability
  else if(liveProbability < 1)
    return Math.random()< liveProbability
  else if(liveProbability > 10)
    return Math.random()*100 < liveProbability
}


//判断是PC还是移动
/*
* true:PC
* false:移动
*/
export function isPC() {
  const userAgentInfo = navigator.userAgent;//用户设备
  const Agents = [//移动端设备
    "Android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod"
    ];
  return Agents.every(e=>!userAgentInfo.includes(e));
}


//随机rgb - //低饱和
export const randomRGB = () =>{
  const randint = Math.floor(Math.random()*255)
  const result = [randint-50,randint,randint+50].sort(()=>{
    return (0.5-Math.random())
  })
  return `rgb(${result})`
}


//邮箱验证
export const mailReg = mail => {
	return mail!=''?
	/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(mail)
	: true
}
//替换hash
export const changeHash = (key,value)=>{
	let oldHash = window.location.hash.toString();
	let re=eval('/('+ key+'=)([^&]*)/gi');
	let newHash = oldHash.replace(re,key+'='+value);
	window.location.hash=newHash
}

//dateFormat("YYYY-mm-dd HH:MM", date)
//时间格式转换

export const dateFormat = (fmt, date) =>{
  let ret;
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "M+": (date.getMonth() + 1).toString(),     // 月
      "D+": date.getDate().toString(),            // 日
      "h+": date.getHours().toString(),           // 时
      "m+": date.getMinutes().toString(),         // 分
      "s+": date.getSeconds().toString()          // 秒
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

export const getWeekday = date => {
  if(!date)
    data = new Date()
  let b
  switch(date.getDay()){
  	case 0:b="日";break;
  	case 1:b="一";break;
  	case 2:b="二";break;
  	case 3:b="三";break;
  	case 4:b="四";break;
  	case 5:b="五";break;
  	default:b="六";
  }
  return `周${b}`
}

/**
 * n位随机数
 */
 export const RANDOM = n =>{
  var rnd=""
  for(var i=0;i<n;i++)
     rnd+=Math.floor(Math.random()*10);
  return Number(rnd)
}


export const exportFile = (url,fileName) =>{
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link); //下载完成移除元素
  window.URL.revokeObjectURL(url);
}

/**
 * blob转64
 */
export const blobToBase64 = blob => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = (e) => {
      resolve(e.target.result)
    }
    fileReader.readAsDataURL(blob)
    fileReader.onerror = () => {
      reject(new Error('blobToBase64 error'))
    }
  })
}
/**
 * url转图片
 */
export const urlToBase64 = url => {
  return new Promise ((resolve,reject) => {
    let image = new Image()
    image.onload = function() {
      let canvas = document.createElement('canvas')
      canvas.width = 100
      canvas.height = 100
      canvas.getContext('2d').drawImage(image, 0, 0)
      let result = canvas.toDataURL('image/png')
      resolve(result)
    }
    image.setAttribute("crossOrigin",'Anonymous')
    image.src = url
    image.onerror = () => {
      reject(new Error('urlToBase64 error'))
    }
  })
}


export const timeSleep = (time) => {
  return new Promise(success=>{
    setTimeout(()=>{
      success('')
    },time)
  })
}